package com.krtech.wecard.utils;

import org.apache.tomcat.util.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.stereotype.Component;

import java.security.Security;
import java.security.spec.AlgorithmParameterSpec;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

@Component
public class WxBizDecryptUtils {
    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    public static String wxDecrypt (String encrypted, String sessionKey, String iv) {
        try {
            byte[] encrypData = Base64.decodeBase64(encrypted);
            byte[] ivData = Base64.decodeBase64(iv);
            byte[] sKey = Base64.decodeBase64(sessionKey);
            String decrypt = decrypt(sKey,ivData,encrypData);
            return decrypt;
        }catch (Exception e){
            e.printStackTrace();
        }
        return "";
    }

    public static String decrypt(byte[] key, byte[] iv, byte[] encData) throws Exception {
        //解析解密后的字符串
        String resultString = null;
        AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            resultString = new String(cipher.doFinal(encData), "UTF-8");
        } catch (Exception e) {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            resultString = new String(cipher.doFinal(encData), "UTF-8");
        }
        return resultString;
    }
}
